//1.渲染数据
let content = document.querySelector('.content');
let center = document.querySelector('.center');
list.forEach((ele) => {
  let li = document.createElement('li');
  center.append(li);
  function selectbox() {
    if (ele.select === true) {
      return 'checked';
    } else {
      return false;
    }
  }
  li.innerHTML = `
  <div class="select">
            <input type="checkbox" ${selectbox()}/>
          </div>
          <div class="pic">
            <img src="${ele.pic}" alt="" />
          </div>
          <div class="name">${ele.name}</div>
          <div class="price">￥ <span>${ele.price}.00</span></div>
          <div class="number">
            <button>-</button>
            <input type="text" value="${ele.buy_num}" data-maxnum="${
    ele.number
  }"/>
            <button>+</button>
          </div>
          <div class="subtotal">￥ <span></span></div>
          <div class="del">
            <button>删除</button>
          </div>
  `;
});
//渲染底部
let bottom = document.createElement('div');
bottom.className = 'bottom';
center.after(bottom);
bottom.innerHTML = `
<p>总购买数量: </p>
        <p>
          <button class="pay">去结算</button>
          <button class="clear">清空购物车</button>
          <button class="clear_select">删除所有已选中</button>
          <button class="list">返回列表页</button>
        </p>
        <p>总价格 : ￥ <span></span></p>
`;

//2. 能够全选反选同时总价 总购买数量变化
//全选按钮
let allinput = document.querySelector('.top input');
//五个选项
let select = [...document.querySelectorAll('.select>input')];
//如果全选是选中状态，每一个选项都要选上
//如果全选是未选中状态，每一个都不选
allinput.addEventListener('click', () => {
  select.forEach((ele) => {
    ele.checked = allinput.checked;
  });
  // 更新底部总数量和总价的变化
  updateBottomTotal();
});
// 给下面的五个绑定事件
select.forEach((ele) => {
  ele.addEventListener('click', () => {
    //记录选中的个数
    let count = 0;
    select.forEach((a) => {
      if (a.checked) {
        count++;
      }
    });
    //当选中的数量等于选项总数量时,认为当前全选
    allinput.checked = count === select.length;
  });
});
//单个商品数量能够加减
let li = document.querySelectorAll('li');
li.forEach((item) => {
  //获取-
  let reduce = item.querySelector('.number>button:first-child');
  //获取+
  let add = item.querySelector('.number>button:last-child');
  let input = item.querySelector('.number>input');
  //获取单个商品的单价
  let singlePrice = parseFloat(item.querySelector('.price>span').innerText);
  //获取单个商品的总价
  let subtotal = item.querySelector('.subtotal>span');
  //更新单个商品的数量和价格变化
  updateSubtotal(input, singlePrice, subtotal);
  let maxNum = parseInt(input.getAttribute('data-maxnum')); // 获取单个商品可购买最大数量
  reduce.addEventListener('click', () => {
    if (input.value > 1) {
      input.value--;
      updateSubtotal(input, singlePrice, subtotal);
      updateBottomTotal();
    }
  });

  add.addEventListener('click', () => {
    if (input.value < maxNum) {
      input.value++;
      updateSubtotal(input, singlePrice, subtotal);
      updateBottomTotal();
    }
  });
});

//更新单个总价
function updateSubtotal(input, singlePrice, subtotal) {
  let num = parseInt(input.value);
  if (isNaN(num)) num = 1;
  subtotal.innerText = (singlePrice * num).toFixed(2);
}

//选中/取消选中商品
select.forEach((ele) => {
  ele.addEventListener('click', () => {
    updateBottomTotal();
  });
});

//删除单个商品
let delBtns = document.querySelectorAll('.del>button');
delBtns.forEach((btn) => {
  btn.addEventListener('click', (e) => {
    let li = e.currentTarget.parentNode.parentNode;
    li.remove();

    updateBottomTotal();
  });
});

//删除选中商品
let clearSelect = document.querySelector('.clear_select');
clearSelect.addEventListener('click', () => {
  let selectedLis = [];
  for (let i = 0; i < select.length; i++) {
    if (select[i].checked) {
      let li = select[i].parentNode.parentNode;
      selectedLis.push(li);
    }
  }

  selectedLis.forEach((li) => {
    li.remove();
  });

  updateBottomTotal();
});

//清空购物车
let clearBtn = document.querySelector('.clear');
clearBtn.addEventListener('click', () => {
  let lis = document.querySelectorAll('li');
  lis.forEach((li) => {
    li.remove();
  });

  updateBottomTotal();
});

updateBottomTotal();
//更新底部总价格和数量变化
function updateBottomTotal() {
  let selectedLis = [...document.querySelectorAll('li')].filter((li) =>
    li.querySelector('.select>input:checked')
  );

  let totalNumber = 0;
  let totalPrice = selectedLis.reduce((prev, item) => {
    let price = parseFloat(item.querySelector('.subtotal>span').textContent);
    let number = parseInt(item.querySelector('.number>input').value);
    totalNumber += number;
    return prev + price;
  }, 0);

  let allnum = document.querySelector('.bottom>p:first-child');
  allnum.innerHTML = `总购买数量:${totalNumber}`;

  let totalPriceEle = document.querySelector('.bottom>p:last-child>span');
  totalPriceEle.innerHTML = totalPrice.toFixed(2);
}
